<script setup lang="ts">
import type { CustomDialogInstance } from '@/types'
import type { ListItem, SaveParams } from '../type'
import { MAINTENANCE_RESULT, MAINTENANCE_RESULT_TEXT } from '../constant'

import type { FormInstance, FormRules } from 'element-plus'
import EquipmentSelect from '@/components/EquipmentSelect/EquipmentSelect.vue'

defineOptions({ name: 'OperateModal' })

const props = defineProps<{
  modalData: ListItem
  readonly: boolean
}>()
const emit = defineEmits<{
  (e: 'open'): void
  (e: 'close'): void
  (e: 'saveSuccess'): void
}>()

const formRef = ref<FormInstance>()
const dialogRef = ref<CustomDialogInstance>()
const formData = ref({
  result: MAINTENANCE_RESULT.NORMAL,
} as unknown as SaveParams)
const rules: FormRules = {
  equipmentId: [
    { required: true, message: '请选择设备', trigger: 'change' },
  ],
  num: [
    { required: false, message: '请输入设备编号', trigger: 'blur' },
  ],
  manufacturer: [
    { required: false, message: '请输入生产厂商', trigger: 'blur' },
  ],
  installationTime: [
    { required: false, message: '请选择安装时间', trigger: 'change' },
  ],
  installationAddr: [
    { required: false, message: '请输入安装位置', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择维护类型', trigger: 'change' },
  ],
  time: [
    { required: true, message: '请选择维护时间', trigger: 'change' },
  ],
  content: [
    { required: true, message: '请输入维护内容', trigger: 'blur' },
  ],
  reason: [
    { required: true, message: '请输入维护原因', trigger: 'blur' },
  ],
  result: [
    { required: true, message: '请选择维护结果', trigger: 'change' },
  ],
  executeTime: [
    { required: true, message: '请选择执行时间', trigger: 'change' },
  ],
  executeUser: [
    { required: true, message: '请选择执行人', trigger: 'blur' },
  ],
}

const isViewing = computed(() => {
  return props.readonly
})
const isEditing = computed(() => {
  return !props.readonly && !!props.modalData.id
})
const modalTitle = computed(() => {
  if (isViewing.value) {
    return '查看设备维护信息'
  }
  else if (isEditing.value) {
    return '修改设备维护信息'
  }
  else {
    return '新增设备维护信息'
  }
})

async function clickConfirm(done: () => void) {
  const isValid = await formRef.value?.validate().catch(() => {
    done()
  })
  if (isValid) {
    const params = toValue(formData)
    try {
      await equipmentMaintenanceApi.saveEquipmentMaintenance(params)
      done()
      close()
      ElMessage.success('保存成功')
      emit('saveSuccess')
    }
    finally {
      done()
    }
  }
}

async function getEquipmentInfoDetail() {
  const { data } = await equipmentInfoApi.getEquipmentDetailById(
    unref(formData).equipmentId,
  )
  formData.value = {
    ...formData.value,
    equipmentId: +data.id,
    num: data.num,
    manufacturer: data.manufacturer,
    installationTime: data.installationTime,
    installationAddr: data.installationAddr,
  }
}

function handleChangeEquipmentId(id: number) {
  formData.value.equipmentId = id
  getEquipmentInfoDetail()
}

async function open() {
  if (Object.keys(props.modalData).length > 0) {
    // 修改或查看
    formData.value = {
      ...formData.value,
      ...props.modalData,
    }
  }
  else {
    formData.value = {} as SaveParams
  }
  formRef.value?.resetFields()
  await nextTick()
  dialogRef.value?.open()
}
async function close() {
  dialogRef.value?.close()
}

function onClose() {
  formRef.value?.resetFields()
  emit('close')
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="modalTitle"
    width="780px"
    need-saving
    no-max-height
    :show-confirm-button="!readonly"
    @close="onClose"
    @confirm="clickConfirm"
  >
    <ElForm ref="formRef" :disabled="readonly" label-width="90px" :model="formData" :rules="rules">
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="设备名称" prop="equipmentId">
            <ElInput v-if="isViewing" v-model="formData.name" placeholder="请输入设备名称" />
            <EquipmentSelect v-else v-model="formData.equipmentId" @change="handleChangeEquipmentId" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="设备编号" prop="num">
            <ElInput v-model="formData.num" disabled placeholder="请输入设备编号" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="生产厂家" prop="manufacturer">
            <ElInput v-model="formData.manufacturer" disabled placeholder="请输入设备厂商" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="安装时间" prop="installationTime">
            <ElInput v-model="formData.installationTime" disabled placeholder="请输入安装时间" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="安装位置" prop="installationAddr">
            <ElInput v-model="formData.installationAddr" disabled placeholder="请输入安装地点" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="维护类型" prop="type">
            <DictionaryPicker v-model="formData.type" code="WEI_HU_LEI_XING" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="维护时间" prop="time">
            <ElDatePicker
              v-model="formData.time"
              type="date"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              placeholder="请选择维护时间"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="24">
          <ElFormItem label="维护内容" prop="content">
            <ElInput v-model="formData.content" class="el-input__wrapper !px-0" type="textarea" placeholder="请输入维护内容" show-word-limit :maxlength="100" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="24">
          <ElFormItem label="维护原因" prop="reason">
            <ElInput v-model="formData.reason" class="el-input__wrapper !px-0" type="textarea" placeholder="请输入维护原因" show-word-limit :maxlength="100" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="24">
          <ElFormItem label="备注" prop="remark">
            <ElInput v-model="formData.remark" class="el-input__wrapper !px-0" type="textarea" placeholder="请输入备注" show-word-limit :maxlength="100" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="维护结果" prop="result">
            <ElSelect v-model="formData.result" placeholder="请选择维护结果">
              <ElOption :label="MAINTENANCE_RESULT_TEXT.NORMAL" :value="MAINTENANCE_RESULT.NORMAL" />
              <ElOption :label="MAINTENANCE_RESULT_TEXT.EXCEPTION" :value="MAINTENANCE_RESULT.EXCEPTION" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="执行时间" prop="executeTime">
            <ElDatePicker
              v-model="formData.executeTime"
              type="datetime"
              placeholder="请选择执行时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="12">
          <ElFormItem label="执行人" prop="executeUser">
            <ElInput v-model="formData.executeUser" clearable placeholder="请输入执行人" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </CustomDialog>
</template>
